# -- coding: utf-8 --
from selenium.webdriver.common.by import By


class DataParser:

    @classmethod
    def read_csv(cls, path, symbol):
        """
        读取某个csv格式文件，返回不带注释及空行的内容列表
        :param path: 要读取的csv文件路径
        :param cs: 注释所用的符号，比如#或者//等
        :return: 结果列表
        """
        with open(path, encoding='utf8') as file:
            contents = file.readlines()

        result = []
        for item in contents:
            temp = item.strip()
            if not temp.startswith(symbol) and temp!='':
                if symbol in temp:
                    rl = temp.split(symbol)[0].strip()
                    result.append(rl)
                else:
                    result.append(temp)
        return result

    @classmethod
    def read_json(cls, path):
        """
        该方法用于读取一个标准的json文件，由于使用了json5的库所以可以支持//以及/*注释*/这样的注释，返回python的基本数据类型
        :param path:该json文件的路径及文件名
        :return:python数据类型对象
        """
        import json5
        with open(path, encoding='utf8') as file:
            contents = json5.load(file)
        return contents


class Action:

    driver = None

    def open_browser(self, browser):
        """
        打开浏览器，生成浏览器驱动对象
        :param browser: 浏览器名称，是字符串
        :return: None
        """
        from selenium import webdriver
        driver = self.driver   # 属性本地化，可以减少self的使用
        if hasattr(webdriver, browser):
            driver = getattr(webdriver, browser)()
        else:
            driver = webdriver.Firefox()
        driver.implicitly_wait(5)
        driver.maximize_window()
        self.driver = driver

    def open_page(self, url):
        self.driver.get(url)

    def get_element(self, locator):
        """
        用于获取页面元素对象，返回找到的元素对象
        :param locator: 定位器，格式为by=what的字符串
        :return: 元素对象
        """
        by = str(locator).split('=')[0]  # 获取元素定位方式的字符串
        attr = str(locator).split('=')[1]  # 获取元素定位方式对应的属性值
        return self.driver.find_element(getattr(By, by), attr)  # 通过反射机制动态地获得元素定位方式对象

    def input(self, locator, value):
        element = self.get_element(locator)
        element.click()
        element.clear()
        element.send_keys(value)

    def click(self, locator):
        element = self.get_element(locator)
        element.click()

    def sleep(self, second):
        import time
        time.sleep(int(second))

    def confirm_alert(self):
        self.driver.switch_to.alert.accept()

    def close_browser(self):
        self.driver.close()
        self.driver = None   # 彻底关闭


def run():
    script = DataParser.read_csv('../scripts/demo01.csv', '# ')
    map = DataParser.read_json('../scripts/map.json')
    action = Action()  # 实例化动作类
    for step in script:
        ckw = step.split(',')[0]  # 获取中文关键字
        params = step.split(',')[1:]  # 获取从第一项之后的所有内容作为参数,它是一个列表
        temp = []
        if len(params) > 0:
            for item in params:
                temp.append(item.strip())
        keyword = map[ckw]  # 根据映射字典获取英文关键字
        if hasattr(action, keyword):
            getattr(action, keyword)(*tuple(temp))  # 将列表先转化为元组，再通过*进行解包当做参数传递

if __name__ == '__main__':
    import random
    print(random.randint(1,3))


